package com.zq.api.controller;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.zq.common.annotation.Log;
import com.zq.common.constant.MysqlConstant;
import com.zq.common.constant.TagConstant;
import com.zq.common.core.context.BaseContext;
import com.zq.common.core.domain.Result;
import com.zq.common.enums.BusinessEnum;
import com.zq.common.enums.BusinessType;
import com.zq.common.enums.OperatorType;
import com.zq.common.exception.base.BaseException;
import com.zq.server.api.dao.UserTagMapper;
import com.zq.server.api.domain.entity.ApiTag;
import com.zq.server.api.domain.vo.TagListVo;
import com.zq.server.api.service.ApiTagService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/user/tag")
@Api(tags = "标签相关接口")
@Slf4j
public class ApiTagController {
    @Autowired
    private UserTagMapper userTagMapper;
    @Autowired
    private ApiTagService tagService;

    @PostMapping("/tags")
    public Result<String> addTag(@RequestBody ApiTag tag) {
        try {
            tagService.save(tag);
            return Result.success(TagConstant.TAG_SAVE_SUCCEED);
        } catch (Exception e) {
            return Result.error(TagConstant.TAG_SAVE_ERROR);
        }
    }

    /**
     * 获取所有标签
     *
     * @return 获取所有标签
     */
    @ApiOperation("获取标签集合")
    @GetMapping("/getTagList")
    public Result<List<ApiTag>> getTagList() {
        try {
            // 从数据库中获取所有标签
            List<ApiTag> tagList = tagService.getUserTaglist();
            return Result.success(tagList);
        } catch (BaseException e) {
            // 记录错误日志
            log.error("Failed to retrieve tag list from database", e);
            // 抛出异常，让调用者处理
            throw new BaseException(MysqlConstant.GET_LIST_ERROR);
        }
    }

    /**
     * 添加标签
     *
     * @return 添加标签
     */
    @ApiOperation("获取用户个人标签")
    @GetMapping("/getUserTagList")
    public Result<List<TagListVo>> getUserTagList() {
        Long userId = BaseContext.getCurrentId();
        List<TagListVo> tagListVos = userTagMapper.getUserTagList(userId);
        return Result.success(tagListVos);
    }

    @ApiOperation("用户修改标签")
    @PostMapping("/addTagList")
    @Log(title = "修改标签" , businessType = BusinessType.UPDATE ,operatorType = OperatorType.MOBILE)
    public Result addUserTagList(@RequestBody int[] tagList) {
        Boolean responseSave = tagService.saveListTag(tagList);
        if (responseSave) {
            return Result.success(BusinessEnum.SUCCESS);
        }
        return Result.error(BusinessEnum.TAG_GET_TAG_ERROR);
    }
}
